const db = require('../db/index')

// 主页
exports.index=(req,res)=>{
  // 接收表单数据
  // let userinfo = req.body // post
  let sql
  // 判断是都有值
  // if(Object.keys(userinfo).length>0?true:false) {
  //   sql = `select * from zh_tab where tabname = ${userinfo.title}`
  // }else {
  // }
  sql = 'select * from zh_tab'
  db.query(sql,function (err,results) {
    if(err) return res.send({code:1,msg:'错误'})
    let list = {
      title:'导航栏',
      data:results
    }
    res.send({
        code: 0,
        data:list,
        msg: 'ok'
      })
    // console.log(results);
  })
}

// 导航列表文章详情/文章搜索
exports.list=(req,res)=>{
  let userinfo = req.body
  if(userinfo && userinfo.info_title) {
    sql = `select * from zh_info where info_title = ?`
  }else {
    sql = `select * from zh_info where tab_id = ?`
  }
  db.query(sql,userinfo && userinfo.info_title?userinfo.info_title:userinfo.tab_id,function (err,results) {
    if(err) res.send({code:1,msg:'错误'})
    if(results.length<=0) res.send({code:1,msg:'未查询到文章！'})

    res.send({
      code: 0,
      data:results,
      msg: 'ok'
    })
  })
}

// 导航栏
exports.catitems = (req,res)=>{
  let sql
  sql = 'select * from zh_navigation'

  db.query(sql,function (err,results) {
    if(err) res.send({code:1,msg:'获取分类失败！'})
    if(results.length<=0) res.send({code:1,msg:'未查询到分类列表！'})
    res.send({
      code:0,
      data:results,
      msg:'ok'
    })
  })
}

// 商品列表

exports.goodsSerch = (req,res)=>{
  /**
   * query: string : 关键字
   * cid : string : 分类id
   * page:number
   */
  let query = req.query
  let sql
  if (query && query.cid) {
    sql = `select * from zh_goods where cat_id = ${query.cid}`
  }else {
    sql = 'select * from zh_goods'
  }
  let data = [] // 返回回来的值
  db.query(sql,function (err,resulets) {
    if(err) res.send({code:1,msg:'获取商品失败！'})
    if(resulets.length<=0) res.send({code:1,msg:'未查询到商品列表！'})
    if (query.pagesize) { // 需要数量
      for(let i=0;i<query.pagesize;i++){
        data.push(resulets[i])
      }
    }else { // 如果没有输入的是话；默认一定数量
      for(let i=0;i<10;i++){
        data.push(resulets[i])
      }
    }
    res.send({
      code:0,
      total:resulets.length,
      pagesize:query.pagesize,
      pagenum:Math.ceil(resulets.length/query.pagesize),
      data:data,
      msg:'ok'
    })
  })
}
